import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'


Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/login/login.vue') // 路由懒加载
  },
  {
    name: 'main',
    path: '/',
    component: () => import('@/layout'),
    redirect: '/dashbord',
    children: [
      {
        name: 'Dashbord',
        path: '/dashbord',
        component: () => import('@/views/dashbord') // 路由懒加载
      },
      // {
      //   name: 'Users',
      //   path: '/users',
      //   component: () => import('@/views/users') // 路由懒加载
      // },
    ]
  },
  {
    name: '404',
    path: '*', // * 可以 匹配任何路径， 但是前提是 router 中没有相应的路径配置才可以， 
    component: () => import('@/views/404')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//自定义方法解决 动态路由重复加载问题
//自定义一个 $addRoutes 方法 在这个方法中重新创建新的router 实例
//此方法 只适用于 history 模式
router.$addRoutes = (params) => {
  router.matcher = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: params
  }).matcher
  //router.addRoutes(params)
}
//导航守卫
router.beforeEach(function (to, from, next) {
  if (to.path === '/login') {
    next()
  } else {
    if (store.state.token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
